package com.team.instantsharing.file

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.event.ProgressEvent
import com.amazonaws.event.ProgressListener
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.GetObjectRequest
import com.amazonaws.services.s3.model.PutObjectRequest
import com.amazonaws.services.s3.model.PutObjectResult
import com.amazonaws.services.s3.model.S3Object
import com.amazonaws.services.s3.model.S3ObjectInputStream
import com.amazonaws.services.s3.model.StorageClass;
import com.amazonaws.services.s3.transfer.Upload
import com.team.instantsharing.dto.File;
import com.team.instantsharing.dto.Message;
import com.team.instantsharing.dto.TextFile;
import com.team.instantsharing.ultils.Constant;
import com.team.instantsharing.ultils.FileConvert;
import com.team.instantsharing.ultils.RequestHeader;
import com.team.instantsharing.ultils.ServiceRequest;

import grails.converters.JSON
import grails.plugin.awssdk.AmazonWebService
import grails.util.Holders;

class FileController {

	def grailsApplication = Holders.getGrailsApplication();

	AmazonWebService amazonWebService;

	def saveFileUploaded(){
		File fileUpload = new File();
		fileUpload.setFileName(params.fileName);
		fileUpload.setDateCreate(new Date());
		fileUpload.setFilePath(params.filePath);
		fileUpload.setFileCapacity(Long.parseLong(params.fileCapacity));
		fileUpload.setUserEmail(params.fileUserOwner);
		fileUpload.setFilePermission(Constant.DOCUMENT_PUBLIC);

		RestTemplate restTemplate = new RestTemplate();
		HttpEntity<File> fileUploadEntity = new HttpEntity<File>(fileUpload, RequestHeader.getUserHeader(session.userToken));
		Message saveFileMessage = restTemplate.exchange(Constant.SERVICE_URL + ServiceRequest.SAVE_FILE_UPLOADED, HttpMethod.POST, fileUploadEntity, Message.class).body;
		
		if(saveFileMessage.response.equals(Constant.SAVE_FILE_SUCCESS)){
			Long usedCapacity = session.usedCapacity;
			session.usedCapacity = usedCapacity + fileUpload.getFileCapacity();
			session.usedCapacityString = FileConvert.getDocumentCapacityString(session.usedCapacity);
		}
		Long percent = (int)(session.usedCapacity * 100 / session.availableCapacity);
		render ([info:saveFileMessage.response, usedCapacity:session.usedCapacityString, avaiCapacity:session.availableCapacityString, percent: percent] as JSON)
	}
	
	def shareFile(){
		String fileUrl = params.fileUrl;
		
		RestTemplate restTemplate = new RestTemplate();
		HttpEntity headerEntity = new HttpEntity(fileUrl, RequestHeader.getDefaultHeader());
		File fileDownload = restTemplate.exchange(Constant.SERVICE_URL + ServiceRequest.DOWNLOAD_FILE + Constant.SUFFIX + fileUrl, HttpMethod.GET, headerEntity, File.class).body;
		if (fileDownload.getFileName() == null){
			render view:"/errorPage/error404.gsp";
			return
		}
		else{
			println fileDownload.getFileName() + " - " + fileDownload.getFilePath();
		}
		[fileName: fileDownload.getFileName(), fileUrl: fileUrl]
//		render view:"/errorPage/errorConstruction.gsp";
	}
	
	def downloadFile(){
		String fileUrl = params.fileUrl;
		
		println fileUrl;
		
		RestTemplate restTemplate = new RestTemplate();
		HttpEntity headerEntity = new HttpEntity(fileUrl, RequestHeader.getDefaultHeader());
		File fileDownload = restTemplate.exchange(Constant.SERVICE_URL + ServiceRequest.DOWNLOAD_FILE + Constant.SUFFIX + fileUrl, HttpMethod.GET, headerEntity, File.class).body;
		if (fileDownload.getFileName() != null && fileDownload.getUserEmail() != null){
			String bucketS3 = grailsApplication.config.grails.plugin.awssdk.s3Bucket;
			String accessKeyId = grailsApplication.config.grails.plugin.awssdk.accessKey;
			String secretKey = grailsApplication.config.grails.plugin.awssdk.secretKey;
			
			String filePath = "";
			if (fileDownload.getFilePath() == null || fileDownload.getFilePath() == ""){
				filePath = fileDownload.getUserEmail() + Constant.SUFFIX + fileDownload.getFileName();
			}
			else{
				filePath = fileDownload.getUserEmail() + Constant.SUFFIX + fileDownload.getFilePath() + Constant.SUFFIX + fileDownload.getFileName();
			}
			AWSCredentials myCredentials = new BasicAWSCredentials(accessKeyId, secretKey);
			AmazonS3 s3Client = new AmazonS3Client(myCredentials);
			GetObjectRequest requestGetObj = new GetObjectRequest(bucketS3, filePath);
			S3Object object = s3Client.getObject(requestGetObj);
			S3ObjectInputStream objectContent = object.getObjectContent();
			byte[] outArray = IOUtils.toByteArray(objectContent);
			println outArray.length;
			
			if (outArray) {
				String attachment = "attachment; filename=" + fileDownload.getFileName();
				response.setContentLength(outArray.length);
				response.setHeader("Expires:", "0");
				response.setHeader("Content-Disposition", attachment);
				OutputStream outStream = response.getOutputStream();
				outStream.write(outArray);
				outStream.flush();
			} else {
				render view:"/errorPage/error404.gsp";
				return;
			}
		}
		else{
			render view:"/errorPage/error404.gsp";
			return;
		}
	}
	
	def createTextFile(){
		String userEmail = params.userEmail;
		String fileName = params.fileName;
		String filePath = params.filePath;
		String fileContent = params.fileContent;
		
		TextFile textFile = new TextFile();
		textFile.setUserEmail(userEmail);
		textFile.setFileName(fileName);
		textFile.setFilePath(filePath);
		textFile.setFileContent(fileContent);
		
		RestTemplate restTemplate = new RestTemplate();
		Message message = restTemplate.postForObject(Constant.SERVICE_URL + ServiceRequest.CREATE_TEXT_FILE, textFile, Message.class);
		
		render ([info:message.response] as JSON)
	}
	
	def sendFileLinkToEmail(){
		String userEmail = session.userEmail;
		String fileUrl = params.fileUrl;
		String listEmailReceive = params.listEmailReceive;
		
		RestTemplate restTemplate = new RestTemplate();
		String requestUrl = Constant.SERVICE_URL + ServiceRequest.SEND_EMAIL_SHARE_LINK + "?userEmail=" + userEmail + "&documentUrl=" + fileUrl + "&userEmailShare=" + listEmailReceive;
		restTemplate.getForObject(requestUrl, Message.class);
		
		render ([info:"Success"] as JSON)
	}
}
